#!/bin/sh
#author 箱子先生 305170330@qq.com

shDir=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)
. $shDir/backup_config

#检查给定的数据库名称是否为要忽略的数据库，是返回1或2，不是返回0
function isIgnoreDb()
{
        local db
        for db in ${ignoreDbs[@]}; do
                if [ $1 = $db ]; then
                	return 1
                elif [ $1 = Database ]; then
                	return 2
                fi 
        done
        return 0
}

#检查给定的表名称是否为要忽略的表，是返回1或2，不是返回0
function isIgnoreTable()
{
        local t
        for t in ${ignoreTables[@]}; do
                if [ `echo $1 | grep -i $t` ]; then
                	return 1
                elif [ `echo $1 | grep -i ^Tables_in_.` ]; then
                	return 2
                fi
        done
        return 0
}

#删除旧备份，建立新备份文件夹
[ $saveDays -gt 0 ] && find `dirname $newFolder` -type d -ctime +$saveDays -exec rm -rf {} \;
[ -d $newFolder ] && newFolder="$newFolder.$RANDOM";
mkdir -p $newFolder

#获取数据库列表
dbs=`$MYSQL -h$HOST -u$USER -p$PASSWD <<EOF
show databases;
exit
EOF`

#要备份的表
backupTables=""

ignoredDbs=()
ignoredTables=()

#遍历所有数据库，过滤掉忽略的库，然后遍历每个库的表，去除忽略的表，执行备份
for db in  $dbs; do `isIgnoreDb $db`
	rt=$?
        if [ $rt -eq 0 ]; then
                tbs=`$MYSQL -h$HOST -u$USER -p$PASSWD <<EOF
                        show tables from $db;
                        exit
EOF`
		for t in $tbs; do `isIgnoreTable $t`
			rt=$?
                        if [ $rt -eq 0 ]; then
                        	backupTables="$backupTables $t"
                    	elif [ -n "$reportRecivers" -a $rt -eq 1 ]; then
                    		ignoredTables=(${ignoredTables[@]} $db.$t)
                    	fi
            	done

                #如果该数据库有需要备份的表，执行备份
                if [ -n "$backupTables" ]; then
                $MYSQLDUMP -u$USER -h$HOST -p$PASSWD $DUMPOPTIONS $db $backupTables > $newFolder/$db.sql
                fi

                #清空要备份表
                backupTables=""
        elif [ -n "$reportRecivers" -a $rt -eq 1 ]; then
        		ignoredDbs=(${ignoredDbs[@]} $db)
        fi
done

#发送备份状态邮件
if [ -n "$reportRecivers" ]; then
	nowDate=`date +%Y-%m-%d`;
	tmpFile=tmp.txt;
	echo $nowDate > $tmpFile;
	du -ah $newFolder >> $tmpFile;

	mailContent="\n\n忽略的数据库："
	for db in ${ignoredDbs[@]}; do
		mailContent=$mailContent"\n"$db
	done
	mailContent=$mailContent"\n\n忽略的表："
	for t in ${ignoredTables[@]}; do
		mailContent=$mailContent"\n"$t
	done
    echo -e $mailContent >> $tmpFile
	mail -s ${nowDate}${projectName}备份报告 $reportRecivers < $tmpFile;
	rm -f $tmpFile
fi

